import React, { useEffect, useState } from 'react'
import Navbar from '../../../compounts/navber/Navbar'
import { Avatar, Toast } from 'antd-mobile'
import request from '../../../api/request'
import style from './allDepartments.module.css'
import { useNavigate } from 'react-router-dom'

function Index() {
    const nav = useNavigate()
    const [departments, setDepartments] = useState([])
    const [loading, setLoading] = useState(true)

    // 获取所有科室列表
    const getAllDepartments = () => {
        request.get('/share/knowledgeBase/v1/findDepartment').then((res) => {
            const deptList = res.data.result || []
            setDepartments(deptList)
            setLoading(false)
        }).catch((error) => {
            console.error('获取科室列表失败:', error)
            Toast.show('获取科室列表失败')
            setLoading(false)
        })
    }

    useEffect(() => {
        getAllDepartments()
    }, [])

    // 点击科室跳转到对应的医生列表页
    const handleDeptClick = (dept) => {
        nav(`/keshiDoctor?id=${dept.id}&name=${dept.departmentName}`)
    }

    if (loading) {
        return (
            <div className={style.box}>
                <Navbar title={'全部科室'}></Navbar>
                <div className={style.loading}>加载中...</div>
            </div>
        )
    }

    return (
        <div className={style.box}>
            <Navbar title={'全部科室'}></Navbar>
            
            <div className={style.container}>
                <div className={style.header}>
                    <h2>选择科室</h2>
                    <p>共 {departments.length} 个科室</p>
                </div>
                
                <div className={style.departmentGrid}>
                    {departments.map((dept, index) => (
                        <div 
                            key={dept.id || index} 
                            className={style.departmentItem}
                            onClick={() => handleDeptClick(dept)}
                        >
                            <div className={style.deptIcon}>
                                <Avatar 
                                    src={dept.pic} 
                                    style={{ '--size': '48px' }} 
                                />
                            </div>
                            <div className={style.deptName}>
                                {dept.departmentName}
                            </div>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    )
}

export default Index
